<?php
// +----------------------------------------------------------------------
// | Author: yaoyihong <510974211@qq.com>
// +----------------------------------------------------------------------

namespace app\api\validate;

use app\common\validate\ValidateBase;
use Think\Db;

class Posts extends ValidateBase
{
    // 验证规则
    protected $rule = [
        'category_id' => 'require|number',
        'limit' => 'require|number|between:1,30',
        'sort' => 'requireValidity',
        'keyword' => 'require|chsDash|max:100',
        'posts_id'=> 'require|checkPostsId',
        'open_id'=>'require',
        'type'=>'require'
    ];

    // 验证提示
    protected $message = [
        'category_id.require' => '栏目ID不能为空',
        'category_id.number' => '栏目ID只能是数字',
        'limit.require' => '数据条数不能为空',
        'limit.number' => '数据条数只能是整数',
        'limit.between'=> '数据条数限制1到30之间',
        'keyword.require' => '关键字不能为空',
        'keyword.max' => '关键字长度不能超过100个字符',
        'posts_id.require'=>'文章ID必须',
        'open_id.require'=>'open_id必须'
    ];

    // 应用场景
    protected $scene = [
        'getlist' => ['category_id', 'limit', 'sort'],
        'search' => ['keyword'],
        "add_view"=>['posts_id','open_id','type'=>'require|eq:2'],
        "set_Likes"=>['posts_id','open_id','type'=>'require|eq:1']
    ];

    /**
     * 自定义验证规则 如果字段不为空，则验证合法性
     * return bool|string
     */
    protected function requireValidity($value, $rule, $data, $field)
    {
        if (empty($value)) {
            return true;
        }
        $value = strip_tags($value);
        $value = explode(' ', $value);
        if (!in_array($value[1], ['asc', 'desc'])) {
            return '排序规则不合法';
        }

        return true;
    }
    protected function checkPostsId($value){
        $result = Db::name("Posts")->where(["id"=>$value,"ischeck"=>1,"isdelete"=>0])->select();
        if(empty($result)){
            return "文章不存在";
        }
        return true;
    }
}